package cn.mineserv.video.videoordersystem.utils;

import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class USC2toUTF8 {
    private String str;

    public USC2toUTF8(String str) {
        this.str = str;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public String convertUnicodeToUTF8() {
        String str = this.str;
        Pattern pattern = Pattern.compile("(\\\\u(\\w{4}))");
        Matcher matcher = pattern.matcher(str);

        // 迭代，将str中的所有unicode转换为正常字符
        while (matcher.find()) {
            String unicodeFull = matcher.group(1); // 匹配出的每个字的unicode，比如\u67e5
            String unicodeNum = matcher.group(2); // 匹配出每个字的数字，比如\u67e5，会匹配出67e5

            // 将匹配出的数字按照16进制转换为10进制，转换为char类型，就是对应的正常字符了
            char singleChar = (char) Integer.parseInt(unicodeNum, 16);

            // 替换原始字符串中的unicode码
            str = str.replace(unicodeFull, singleChar + "");
        }
        return str;
    }

    public String convertUTF8ToUnicode() {
        String str = this.str;// 获取用户输入的字符串
        char[] charArray = str.toCharArray();// 获取字符串的字符数组
        StringBuilder builder = new StringBuilder();// 创建字符串构建器
        int al, ah;
        char[] Hexadecimal = {'A', 'B', 'C', 'D', 'E', 'F'};
        for (char c : charArray) {// 遍历字符数组
            Stack<Integer> stack = new Stack<Integer>();
            builder.append("\\u");
            al = c;
            int temp = al;
            int count = 0;
            while (temp != 0) {
                count++;
                temp = temp / 16;
            }
            while (al != 0) {
                ah = al % 16;
                stack.push(ah);
                al = al / 16;
            }
            while ((4 - count) != 0) {
                count++;
                stack.push(0);
            }
            while (!stack.empty()) {
                int k = stack.pop();
                if (k >= 10) {
                    builder.append(Hexadecimal[k - 10]);
                } else {
                    builder.append(k);
                }
            }
        }
        return builder.toString().replace("\\000A", "\\000D\\000A");//
    }

}
